<template>
  <view class="container">
    <!-- 背景图 -->
    <image 
      class="background" 
      src="/static/bg-main.jpg" 
      mode="widthFix"
    ></image>
    
    <view class="left-bar">
      <button @click="handleButtonClick('setting')" class="sidebar-btn setting-btn">
        <i class="icon-setting"></i>
        <span>设置</span>
      </button>
      <button @click="handleButtonClick('skin')" class="sidebar-btn skin-btn">
        <i class="icon-skin"></i>
        <span>皮肤</span>
      </button>
      <button @click="handleButtonClick('daily')" class="sidebar-btn daily-btn">
        <i class="icon-daily"></i>
        <span>每日挑战</span>
      </button>
    </view>
    
    <view class="center">
      <button class="start-btn" @click="handleButtonClick('play')">开始游戏</button>
      <button class="challenge-btn" @click="handleButtonClick('share')">挑战好友</button>
    </view>
    
    <view class="right-bar">
      <!-- 1. 为体力显示区域添加点击事件，当点击时触发handleStaminaClick方法 -->
      <view class="stamina" @click="handleStaminaClick">体力：{{ stamina }}/100</view>
      <button @click="handleButtonClick('top')" class="sidebar-btn top-btn">
        <i class="icon-top"></i>
        <span>排行榜</span>
      </button>
      <button @click="handleButtonClick('award')" class="sidebar-btn award-btn">
        <i class="icon-award"></i>
        <span>奖励</span>
      </button>
    </view>
    
    <!-- 弹窗区域 -->
    <view v-if="currentPopup" class="setting-modal" :class="{ 'modal-enter': isModalEnter }">
      <view class="setting-mask" @click="handleClosePopup"></view>
      <view class="setting-popup-wrap">
        <setting v-if="currentPopup === 'setting'" @close="handleClosePopup" :isBgmPlaying="isBgmPlaying" @toggleBgm="toggleBgm" />
        <skin-popup v-if="currentPopup === 'skin'" @close="handleClosePopup" />
        <daily-challenge v-if="currentPopup === 'daily'" @close="handleClosePopup" />
        <top-popup v-if="currentPopup === 'top'" @close="handleClosePopup" />
      </view>
    </view>
    
    <!-- 引用体力不足弹窗组件 -->
    <stamina-popup 
      :visible="showStaminaPopup" 
      @close="closeStaminaPopup" 
      @recover="recoverStamina"
    />
  </view>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, watchEffect } from 'vue'
import { storageUtil } from '@/utils/storage.js'
import { STORAGE_KEYS } from '@/utils/constants.js'
import setting from '../setting/setting.vue'
import skinPopup from '../skin/skin.vue'
import dailyChallenge from '../daily-challenge/daily-challenge.vue'
import topPopup from '../top/top.vue'
// 导入体力不足弹窗组件
import staminaPopup from '../ad/bullet-stamina-ad.vue'

// 音频对象
const bgmAudio = ref(null)
const clickAudio = ref(null)
const isBgmPlaying = ref(false)

// 弹窗控制
const currentPopup = ref('')
const isModalEnter = ref(false)

// 体力弹窗控制（仅保留显示状态变量）
const showStaminaPopup = ref(false)

// 游戏数据
const stamina = ref(100)

// 体力恢复计时器
let staminaRecoveryTimer = null

// 存储微信小程序存储变化监听函数引用
const wxStorageChangeHandler = () => {
  updateMusicState()
}

// 从存储获取数据
const initData = () => {
  const savedStamina = storageUtil.get(STORAGE_KEYS.stamina, 100)
  stamina.value = Math.min(100, Math.max(0, savedStamina))
}

// 从存储获取声音设置
const getSoundSettings = () => {
  const soundOff = storageUtil.get(STORAGE_KEYS.soundOff, false)
  const musicOff = storageUtil.get(STORAGE_KEYS.musicOff, false)
  return { soundOff, musicOff }
}

// 初始化音频
const initAudio = () => {
  switch (process.env.UNI_PLATFORM) {
    case 'h5':
      // 背景音乐
      bgmAudio.value = new Audio('/static/audio/bgm.mp3')
      bgmAudio.value.loop = true
      
      // 点击音效
      clickAudio.value = new Audio('/static/audio/click.mp3')
      clickAudio.value.volume = 0.7
      break
      
    case 'mp-weixin':
      bgmAudio.value = wx.createInnerAudioContext()
      bgmAudio.value.src = '/static/audio/bgm.mp3'
      bgmAudio.value.loop = true
      
      clickAudio.value = wx.createInnerAudioContext()
      clickAudio.value.src = '/static/audio/click.mp3'
      clickAudio.value.volume = 0.7
      break
  }
}

// 播放点击音效
const playClickSound = () => {
  const { soundOff } = getSoundSettings()
  if (!soundOff && clickAudio.value) {
    switch (process.env.UNI_PLATFORM) {
      case 'h5':
        clickAudio.value.currentTime = 0
        clickAudio.value.play().catch(err => {
          console.log('点击音效播放失败:', err)
        })
        break
        
      case 'mp-weixin':
        clickAudio.value.seek(0)
        clickAudio.value.play()
        break
    }
  }
}

// 触发震动反馈
const triggerVibration = () => {
  switch (process.env.UNI_PLATFORM) {
    case 'h5':
      if (navigator.vibrate) {
        navigator.vibrate(10)
      }
      break
      
    case 'mp-weixin':
      wx.vibrateShort()
      break
  }
}

// 2. 新增体力显示区域点击处理方法
// 当体力不足（小于10）时点击才会弹出体力弹窗
const handleStaminaClick = () => {
  playClickSound()  // 播放点击音效
  triggerVibration()  // 触发震动反馈
  
  // 判断体力是否不足（小于10），满足条件则打开体力弹窗
  if (stamina.value < 10) {
    openStaminaPopup()
  }
}

// 按钮点击处理
const handleButtonClick = (action) => {
  playClickSound()
  triggerVibration()
  
  switch(action) {
    case 'setting':
    case 'skin':
    case 'daily':
    case 'top':
      openPopup(action)
      break
    case 'play':
      if (stamina.value >= 10) {
        stamina.value -= 10
        storageUtil.set(STORAGE_KEYS.stamina, stamina.value)
        goTo('play')
      } else {
        openStaminaPopup()
      }
      break
    case 'share':
      shareToFriend()
      break
    case 'award':
      goTo('award')
      break
  }
}

// 关闭弹窗处理
const handleClosePopup = () => {
  playClickSound()
  triggerVibration()
  closePopup()
}

// 根据设置更新音乐播放状态
const updateMusicState = () => {
  const { soundOff, musicOff } = getSoundSettings()
  if (soundOff && musicOff) {
    playBgm()
  } else if (!soundOff || !musicOff) {
    pauseBgm()
  }
}

// 播放背景音乐
const playBgm = () => {
  if (!bgmAudio.value || isBgmPlaying.value) return
  
  switch (process.env.UNI_PLATFORM) {
    case 'h5':
      bgmAudio.value.play()
        .then(() => {
          isBgmPlaying.value = true
          console.log('背景音乐播放成功')
        })
        .catch(err => {
          console.log('背景音乐播放失败:', err)
          console.log('等待用户交互后再尝试播放')
        })
      break
      
    case 'mp-weixin':
      bgmAudio.value.play()
      isBgmPlaying.value = true
      console.log('背景音乐播放成功')
      break
  }
}

// 暂停背景音乐
const pauseBgm = () => {
  if (!bgmAudio.value || !isBgmPlaying.value) return
  
  switch (process.env.UNI_PLATFORM) {
    case 'h5':
    case 'mp-weixin':
      bgmAudio.value.pause()
      break
  }
  
  isBgmPlaying.value = false
  console.log('背景音乐已暂停')
}

// 初始化体力恢复计时器
const initStaminaRecovery = () => {
  if (staminaRecoveryTimer) {
    clearInterval(staminaRecoveryTimer)
  }
  
  staminaRecoveryTimer = setInterval(() => {
    if (stamina.value < 100) {
      stamina.value += 1
      storageUtil.set(STORAGE_KEYS.stamina, stamina.value)
    }
  }, 60000)
}

// 页面加载完成后初始化
onMounted(() => {
  initData()
  initAudio()
  initStaminaRecovery()
  
  // 监听存储变化，实时更新音乐状态
  const platform = process.env.UNI_PLATFORM
  console.log(`当前是${platform}环境`)
  
  switch (platform) {
    case 'mp-weixin':
      wx.onStorageChange(wxStorageChangeHandler)
      break
      
    case 'h5':
      window.addEventListener('storage', updateMusicState)
      break
  }
  
  // 初始检查并应用设置
  updateMusicState()
  
  // 尝试在用户交互后播放音乐
  if (!isBgmPlaying.value) {
    const tryPlayOnInteraction = () => {
      updateMusicState()
      
      switch (platform) {
        case 'h5':
          document.removeEventListener('click', tryPlayOnInteraction)
          document.removeEventListener('touchstart', tryPlayOnInteraction)
          break
          
        case 'mp-weixin':
          wx.offTouchStart(tryPlayOnInteraction)
          break
      }
    }
    
    switch (platform) {
      case 'h5':
        document.addEventListener('click', tryPlayOnInteraction)
        document.addEventListener('touchstart', tryPlayOnInteraction)
        break
        
      case 'mp-weixin':
        wx.onTouchStart(tryPlayOnInteraction)
        break
    }
  }
})

// 页面卸载时清理
onUnmounted(() => {
  switch (process.env.UNI_PLATFORM) {
    case 'h5':
      if (bgmAudio.value) {
        bgmAudio.value.pause()
        bgmAudio.value = null
      }
      if (clickAudio.value) {
        clickAudio.value = null
      }
      window.removeEventListener('storage', updateMusicState)
      break
      
    case 'mp-weixin':
      if (bgmAudio.value) {
        bgmAudio.value.stop()
        bgmAudio.value.destroy()
        bgmAudio.value = null
      }
      if (clickAudio.value) {
        clickAudio.value.stop()
        clickAudio.value.destroy()
        clickAudio.value = null
      }
      wx.offStorageChange(wxStorageChangeHandler)
      break
  }
  
  // 清除体力恢复计时器
  if (staminaRecoveryTimer) {
    clearInterval(staminaRecoveryTimer)
    staminaRecoveryTimer = null
  }
})

// 控制背景音乐播放/暂停
const toggleBgm = () => {
  if (!bgmAudio.value) return
  
  if (isBgmPlaying.value) {
    pauseBgm()
    storageUtil.set(STORAGE_KEYS.musicOff, false)
  } else {
    playBgm()
    storageUtil.set(STORAGE_KEYS.musicOff, true)
  }
}

// 打开弹窗
const openPopup = (type) => {
  currentPopup.value = type
  setTimeout(() => {
    isModalEnter.value = true
  }, 10)
}

// 关闭弹窗
const closePopup = () => {
  isModalEnter.value = false
  setTimeout(() => {
    currentPopup.value = ''
  }, 300)
}

// 体力不足弹窗控制方法
const openStaminaPopup = () => {
  showStaminaPopup.value = true
}

const closeStaminaPopup = () => {
  showStaminaPopup.value = false
}

// 恢复体力方法
const recoverStamina = () => {
  uni.showToast({
    title: '体力恢复功能开发中',
    icon: 'none'
  })
  closeStaminaPopup()
}

// 页面跳转
const goTo = (page) => {
  const forbiddenPages = ['setting', 'skin', 'daily-challenge', 'top']
  if (forbiddenPages.includes(page)) return
  
  uni.navigateTo({ url: `/pages/${page}/${page}` })
}

// 分享功能
const shareToFriend = () => {
  switch (process.env.UNI_PLATFORM) {
    case 'h5':
      uni.showToast({ title: '分享功能开发中', icon: 'none' })
      break
      
    case 'mp-weixin':
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
      
      // 监听分享给好友
      wx.onShareAppMessage(() => {
        return {
          title: '来挑战这款游戏吧！',
          path: '/pages/index/index',
          imageUrl: '/static/share-img.png'
        }
      })
      
      // 监听分享到朋友圈
      wx.onShareTimeline(() => {
        return {
          title: '我正在玩这款游戏，一起来挑战！',
          query: 'from=timeline',
          imageUrl: '/static/share-img.png'
        }
      })
      break
  }
}

// 监听弹窗状态变化
watch(currentPopup, (newVal) => {
  switch (process.env.UNI_PLATFORM) {
    case 'h5':
      if (newVal) {
        document.body.style.overflow = 'hidden'
      } else {
        document.body.style.overflow = ''
      }
      break
      
    case 'mp-weixin':
      // 小程序无需处理body overflow
      break
  }
})

// 监听localStorage变化，实时更新音乐状态
watchEffect(() => {
  updateMusicState()
})
</script>

<style scoped>
/* 容器样式 */
.container {
  display: flex;
  flex-direction: row;
  height: 100vh;
  position: relative;
  width: 100%;
  box-sizing: border-box;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  filter: brightness(0.9);
  object-fit: cover;
}

.left-bar, .right-bar {
  width: 20vw;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding-top: 40rpx;
}

.center {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 按钮样式 */
.sidebar-btn {
  width: 16vw;
  margin: 15rpx 0;
  padding: 18rpx 0;
  border-radius: 12rpx;
  border: none;
  font-size: 28rpx;
  font-weight: 500;
  color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
  position: relative;
  overflow: hidden;
}

.sidebar-btn::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.1);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.sidebar-btn:active::after {
  opacity: 1;
}

.sidebar-btn i {
  font-size: 40rpx;
  margin-bottom: 10rpx;
}

.setting-btn {
  background: linear-gradient(135deg, #6B7280, #4B5563);
}

.skin-btn {
  background: linear-gradient(135deg, #EC4899, #8B5CF6);
}

.daily-btn {
  background: linear-gradient(135deg, #F59E0B, #FBBF24);
}

.top-btn {
  background: linear-gradient(135deg, #10B981, #34D399);
  margin-top: 20rpx;
}

.award-btn {
  background: linear-gradient(135deg, #8B5CF6, #4F46E5);
  margin-top: 15rpx;
}

.start-btn, .challenge-btn {
  width: 60vw;
  margin: 25rpx 0;
  padding: 25rpx 0;
  font-size: 38rpx;
  font-weight: bold;
  border-radius: 15rpx;
  border: none;
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.25);
  position: relative;
  overflow: hidden;
}

.start-btn:disabled {
  background: linear-gradient(135deg, #94a3b8, #64748b);
  cursor: not-allowed;
}

.start-btn::before, .challenge-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: all 0.6s ease;
}

.start-btn:hover::before, .challenge-btn:hover::before {
  left: 100%;
}

.start-btn:not(:disabled) {
  background: linear-gradient(135deg, #165DFF, #0EA5E9);
}

.start-btn:not(:disabled):active {
  background: linear-gradient(135deg, #0F4CD1, #0284C7);
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
}

.challenge-btn {
  background: linear-gradient(135deg, #EC4899, #F43F5E);
}

.challenge-btn:active {
  background: linear-gradient(135deg, #DB2777, #E11D48);
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
}

/* 弹窗样式 */
.setting-modal {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.setting-modal.modal-enter {
  opacity: 1;
}

.setting-mask {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: 1001;
}

.setting-popup-wrap {
  position: relative;
  z-index: 1002;
  width: 70vw;
  max-height: 80vh;
  background-color: white;
  border-radius: 15rpx;
  transform: scale(0.8);
  transition: transform 0.3s ease;
}

.setting-modal.modal-enter .setting-popup-wrap {
  transform: scale(1);
}

/* 图标样式 */
.icon-setting::before { content: "⚙️"; }
.icon-skin::before { content: "🎨"; }
.icon-daily::before { content: "📅"; }
.icon-top::before { content: "🏆"; }
.icon-award::before { content: "🎁"; }

/* 3. 为体力显示区域添加可点击样式，提示用户该区域可点击 */
.stamina {
  color: #fff;
  font-size: 28rpx;
  margin-bottom: 20rpx;
  padding: 10rpx 15rpx;
  border-radius: 8rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
  cursor: pointer; /* 显示手型光标，提示可点击 */
  transition: background-color 0.2s ease; /* 添加过渡效果 */
}

/* 点击时的反馈样式 */
.stamina:active {
  background-color: rgba(255, 255, 255, 0.1);
}
</style>